package com.elite.groovy.kh;

import org.springframework.util.Base64Utils;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

public class DHAESUtil {
    private static final String KEY_ALGORITHM = "AES";
    private static final String DEFAULT_CIPHER_ALGORITHM = "AES/ECB/PKCS5Padding";
    private static final String CHARSET = "UTF-8";

    public DHAESUtil() {
    }

    public static String encrypt(String content, String password) throws NoSuchPaddingException, NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        byte[] byteContent = content.getBytes("UTF-8");
        cipher.init(1, getSecretKey(password));
        byte[] result = cipher.doFinal(byteContent);
        return Base64Utils.encodeToString(result);
    }

    public static String decrypt(String content, String password) throws NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException, UnsupportedEncodingException, NoSuchPaddingException {
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(2, getSecretKey(password));
        byte[] result = cipher.doFinal(Base64Utils.decodeFromString(content));
        return new String(result, "UTF-8");
    }

    private static SecretKeySpec getSecretKey(String password) throws UnsupportedEncodingException {
        return new SecretKeySpec(password.getBytes("UTF-8"), "AES");
    }

    public static String getKey() throws NoSuchAlgorithmException {
        return generate(16);
    }

    private static String generate(int length) throws NoSuchAlgorithmException {
        char[] chars = new char[length];
        int i = 0;

        for(SecureRandom secureRandom = SecureRandom.getInstanceStrong(); i < length; ++i) {
            int random = secureRandom.nextInt(3);
            chars[i] = random == 0 ? (char)(65 + secureRandom.nextInt(26)) : (random == 1 ? (char)(97 + secureRandom.nextInt(26)) : (char)(48 + secureRandom.nextInt(10)));
        }

        return new String(chars);
    }
}
